package com.chen.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.common.Result;
import com.chen.mapper.PermissionMapper;
import com.chen.mapper.RoleMapper;
import com.chen.mapper.UserMapper;
import com.chen.pojo.Permission;
import com.chen.pojo.RolePermisson;
import com.chen.pojo.User;
import com.chen.pojo.UserRole;
import com.chen.pojo.bean.UserInfo;
import com.chen.service.UserService;
import com.chen.utils.Md5;
import com.chen.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@SuppressWarnings("all")
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    PermissionMapper permissionMapper;

    @Autowired


    @Resource
    RoleMapper roleMapper;

    public User getOpenid(String openid) {
        return userMapper.getQqOpenId(openid);
    }

    public Result<?> login(Integer id) {
        User res = userMapper.selectById(id);

        if (res == null) {
            return Result.error("-1", "用户名或密码错误");

        } else if (res.getStatus() == 0) {
            return Result.error("-2", "未通过审核，请联系管理员");
        }
        // 生成token
        String token = TokenUtils.genToken(res);
        res.setToken(token);
        HashSet<Permission> permissionSet = new HashSet<>();
        //从user_role中通过用户id查询所有的角色信息
        int userId = res.getId();

      UserRole uerRoleIsexist = roleMapper.getUerRoleIsexist(userId);
        if (uerRoleIsexist==null){
            UserRole userRole1=new UserRole();
            userRole1.setUserId(userId);
            userRole1.setRoleId(2);
            roleMapper.insertRole(userRole1.getUserId(),userRole1.getRoleId());
        }

        List<UserRole> userRoles = roleMapper.getByUserRoleUserId(userId);

        List<Permission> permissions=new ArrayList<>();

        for (UserRole userRole : userRoles) {
            //.根据roleId从role_permission表查询出所有的permissionId
            List<RolePermisson> rolePermissions = permissionMapper.getRolePermissionByRoleId(userRole.getRoleId());
            for (RolePermisson rolePermission : rolePermissions) {
                int permissionId = rolePermission.getPermissionId();
                //根据permissionId查询permission信息
                Permission permission = permissionMapper.selectById(permissionId);
                permissionSet.add(permission);
            }
        }

        // 对资源根据id进行排序
        LinkedHashSet<Permission> sortedSet = permissionSet.stream().sorted(Comparator.comparing(Permission::getId)).collect(Collectors.toCollection(LinkedHashSet::new));

        res.setPermissions(sortedSet);
        // 登录成功后 初始化用户信息模板
        UserInfo userInfo = new UserInfo(res);

        return Result.success(userInfo);
    }

    //登录
    @Override
    public Result<?> login(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        queryWrapper.eq("password", user.getPassword());
        User res = userMapper.selectOne(queryWrapper);
        if (res == null) {
            return Result.error("-1", "用户名或密码错误");

        } else if (res.getStatus() == 0) {
            return Result.error("-2", "未通过审核，请联系管理员");
        }
        // 生成token
        String token = TokenUtils.genToken(res);
        res.setToken(token);
        HashSet<Permission> permissionSet = new HashSet<>();
        //从user_role中通过用户id查询所有的角色信息
        int userId = res.getId();
        List<UserRole> userRoles = roleMapper.getByUserRoleUserId(userId);
        List<Permission> permissions=new ArrayList<>();

        for (UserRole userRole : userRoles) {
            //.根据roleId从role_permission表查询出所有的permissionId
            List<RolePermisson> rolePermissions = permissionMapper.getRolePermissionByRoleId(userRole.getRoleId());
            for (RolePermisson rolePermission : rolePermissions) {
                int permissionId = rolePermission.getPermissionId();
                //根据permissionId查询permission信息
                Permission permission = permissionMapper.selectById(permissionId);
                permissionSet.add(permission);
            }
        }

        // 对资源根据id进行排序
        LinkedHashSet<Permission> sortedSet = permissionSet.stream().sorted(Comparator.comparing(Permission::getId)).collect(Collectors.toCollection(LinkedHashSet::new));

        res.setPermissions(sortedSet);
        // 登录成功后 初始化用户信息模板
        UserInfo userInfo = new UserInfo(res);

        return Result.success(userInfo);
    }


    // 注册
    @Override
    public Result<?> register(User user) {
        //先查询，再注册
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res != null) {
            return Result.error("-2", "用户已存在");
        }
        if (user.getPassword() == null) {
            user.setPassword(Md5.MD5("123456"));
        }
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(date);
        user.setRegtime(format);

        userMapper.insert(user);
        return Result.success();
    }

     //忘记密码
    @Override
    public Result<?> forget(User user) {
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));

        if (res==null) {
            return Result.error("-2", "用户不存在,请前往注册");
        }
        res.setUsername(user.getUsername());
        res.setPassword(user.getPassword());
        userMapper.updateById(res);
        return Result.success();
    }


    //重置密码 默认为123456
    @Override
    public Result<?> reset(User user) {

        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res==null){
            return  Result.error("-2","该用户不存在，请前往注册");
        }
     //res.setPassword(Md5.MD5("123456"));
        res.setPassword("123456");

        userMapper.updateById(res);
        return Result.success();
    }
}
